package com.eatwhat.service;

import com.eatwhat.entity.Category;
import com.eatwhat.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class CategoryService {
    
    @Autowired
    private CategoryMapper categoryMapper;
    
    public List<Category> getAllCategories() {
        return categoryMapper.findAll();
    }
    
    public List<Category> getEnabledCategories() {
        return categoryMapper.findAllEnabled();
    }
    
    public Category getCategoryById(Long id) {
        return categoryMapper.findById(id);
    }
    
    public Category saveCategory(Category category) {
        if (category.getId() == null) {
            if (category.getStatus() == null) {
                category.setStatus(1);
            }
            if (category.getSortOrder() == null) {
                category.setSortOrder(0);
            }
            categoryMapper.insert(category);
        } else {
            categoryMapper.update(category);
        }
        return category;
    }
    
    public void deleteCategory(Long id) {
        // 检查是否有菜品使用此分类
        int count = categoryMapper.countFoodsByCategory(id);
        if (count > 0) {
            throw new RuntimeException("该分类下还有菜品，不能删除");
        }
        categoryMapper.deleteById(id);
    }
}